<?php

namespace app\mos\controller;

use app\common\controller\CardPut;
use app\common\model\Agent;
use app\common\model\CardGeneral;
use app\common\model\CardGive;
use app\common\model\CardGivePutCard;
use app\common\model\CardUserGet;
use app\common\model\Momerchant;
use app\common\model\System;
use app\common\model\WxOpen;
use app\common\model\Merchant;
use app\common\model\CardMember;
use app\merchant\controller\Qrcodes;
use think\Session;
use think\Controller;
use Wechat\Wxobjopen;
use Wechat\Wxobjopentest;

class Mobiletest extends Controller
{

    //获取授权
    /*
     * $card_id
     *
     */
    public function _init()
    {
        if (empty(request()->param('card_id'))) {
            $card_id = request()->param('cardid');
        } else {

            $card_id = request()->param('card_id');
        }
        if ($card_id) {
            $option = $this->options($card_id);
            $appid = $this->getappid($card_id);
        } else {
            $mid = request()->param('mid');
            $option = $this->option($mid);
            $appid = $this->getappidmid($mid);
        }
        $openid = Session::get($appid . "_openid");
       
        if (!$openid) {
            $WxObj = new Wxobjopentest($option);
            //获取授权openid
            $userinfo = $WxObj->getOpenoauthAccessToken();
            if(isset($_GET['code'])){
                var_dump($option);
                var_dump($_GET);
                var_dump($_GET['code']);
                var_dump($userinfo);
                exit();
            }
            //获取授权为空时向微信发送请求
            if (empty($userinfo)) {
                $request = request();
                $callback = $request->url(true);
                $url = $WxObj->getopenOauthCode($callback, '', 'snsapi_base');
            
                exit();
            } else {
                Session::set($option['authorizer_appid'] . "_openid", $userinfo['openid']);
                Session::set("card_openid", $userinfo['openid']);
            }
        }
    }

    //获取openid
    public function getappid($card_id)
    {
        $appid = Session::get($card_id . '_appid');
        if (!$appid) {
            $CardMember = new CardMember();
            $Momerchant = new Momerchant();
            $top_mid = $CardMember->where('card_id', $card_id)->value('top_mid');
            if ($top_mid) {
                $map['id'] = $top_mid;
            } else {
                $CardGeneral = new CardGeneral();
                $map['id'] = $CardGeneral->where('card_id', $card_id)->value('top_mid');
            }
            $mab['id'] = $Momerchant->where($map)->value('wx_open_id');
            $WxOpen = new WxOpen();
            $appid = $WxOpen->where($mab)->value('authorizer_appid');
        }
        return $appid;
    }

    //获取openid
    public function getappidmid($mid)
    {
        $appid = Session::get($mid . '_appid');
        if (!$appid) {
            $CardMember = new CardMember();
            $Momerchant = new Momerchant();
            $Merchant = new Merchant();
            $top_mid = $Merchant->where('id', $mid)->value('top_mid');
            if ($top_mid) {
                $map['id'] = $top_mid;
            } else {
                $CardGeneral = new CardGeneral();
                $map['id'] = $CardGeneral->where('mid', $mid)->value('top_mid');
            }
            $mab['id'] = $Momerchant->where($map)->value('wx_open_id');
            $WxOpen = new WxOpen();
            $appid = $WxOpen->where($mab)->value('authorizer_appid');
        }
        return $appid;
    }

    //获取用户信息（解密CODE）
    public function getusercode($arr)
    {
//        var_dump($arr);

        $options = $this->options($arr['card_id']);
        $WxObj = new Wxobjopen($options);
        $map['card_id'] = $arr['card_id'];
        $codedata['encrypt_code'] = $arr['encrypt_code'];
        $resc = $WxObj->decryptCode($codedata);
//        var_dump($resc);
//        exit();
        if ($resc['errcode'] == 0) {
            $map['code'] = $resc['code'];
            $CardUserGet = new CardUserGet();
            $usercode = $CardUserGet->where($map)->value('code');
//            var_dump($usercode);
            if ($usercode == '') {
                $res = $WxObj->userGetInfo($map);
                if ($res['errcode'] == '0') {
                    $data['card_type'] = 'MEMBER_CARD';
                    $data['mid'] = $this->getmid($arr['card_id']);
                    $data['top_mid'] = $this->gettopmid($arr['card_id']);
                    $data['openid'] = $arr['openid'];
                    $data['card_id'] = $arr['card_id'];
                    $data['nickname'] = $res['nickname'];
                    $data['code'] = $res['membership_number'];
                    $data['bonus'] = $res['bonus'];
                    $data['fire'] = $res['has_active'] == true ? 1 : 0;
                    $data['have'] = $res['user_card_status'] == 'NORMAL' ? 1 : 2;
                    $data['create_time'] = time();
                    $inc = $CardUserGet->allowField(true)->validate(['code'  => 'require|unique:CardUserGet'])->save($data);
//                    if ($inc) {
//                        $this->redirect('carduser/index', $arr);
//                    }
                }
            }
        }
    }

    //
    public function getuserinfo($arr)
    {
        $map['card_id'] = $arr['card_id'];
        $appid = $this->getappid($arr['card_id']);
        $map['openid'] = Session::get($appid . '_openid');
        $map['card_type'] = 'MEMBER_CARD';
        $map['have'] = 1;
        $CardUserGet = new CardUserGet();
        $info = $CardUserGet->where($map)->field('id,openid,card_id,code,qrcode,nickname,name,phone,bonus,balance,have,status,fire,sex,birth,birthday,address,growup')->find();
        return $info;
    }

    //检查激活送券
    public function checkfirecards($arr){
//        file_put_contents('/data2/html/payos/test.txt', 'chfire-1' . json_encode($arr), FILE_APPEND);
        try {
            $CardGive = new CardGive();
            $giveinfo = $CardGive->where(['card_id' => $arr['card_id'], 'statu' => 0])->find();
            //是否赠券
//            file_put_contents('/data2/html/payos/test.txt', 'chfire-2' . json_encode($giveinfo), FILE_APPEND);
            if ($giveinfo) {

                //是否结束  是否领卡时结束
                if ($giveinfo['end_time'] > time() && $arr['get_time'] > $giveinfo['end_time']) {
                    //送券记录
                    $CardGivePutCard = new CardGivePutCard();
                    $giveuser = $CardGivePutCard->where(['code'=>$arr['code'],'card_id'=>$arr['card_id'],'openid'=>$arr['openid']])->find();
//                    file_put_contents('/data2/html/payos/test.txt', 'chfire-3' . json_encode($giveuser), FILE_APPEND);
                    if (!$giveuser) {
                        $CardPut = new CardPut();
                        $data['card_id'] = $arr['card_id'];
                        $data['code'] = $arr['code'];
                        $data['openid'] = $arr['openid'];
                        $data['nickname'] = $arr['nickname'];
                        $data['top_mid'] = $arr['top_mid'];
                        $data['mid'] = $arr['mid'];
                        $data['give_type'] = 'fire_card';
//                        file_put_contents('/data2/html/payos/test.txt', 'chfire-4' . json_encode($data), FILE_APPEND);
                        $CardPut->firecards($data);
                    }
                }
            }
        }catch (\Exception $e){
            $data2 = json_encode(array('code' => '9099', 'message' => $e->getMessage()));
//            file_put_contents('/data2/html/payos/test.txt', 'chfire-5' . json_encode($data2), FILE_APPEND);
        }
    }

    /* 获取创建该卡券的门店id
     *
     * $card_id
     *
     */
    public function getmid($card_id)
    {
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $top_mid = $CardMember->where(['card_id' => $card_id])->value('mid');
        if (empty($top_mid)) {
            $top_mid = $CardGeneral->where(['card_id' => $card_id])->value('mid');
            return $top_mid;
        } else {
            return $top_mid;
        }
    }

    /* 获取创建该卡券的商户id
     *
     * $card_id
     *
     */
    public function gettopmid($card_id)
    {
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $top_mid = $CardMember->where(['card_id' => $card_id])->value('top_mid');
        if (empty($top_mid)) {
            $top_mid = $CardGeneral->where(['card_id' => $card_id])->value('top_mid');
            return $top_mid;
        } else {
            return $top_mid;
        }
    }

    public function get_top_mid($mid){
        $Merchant = new Merchant();
        $top_mid = $Merchant->where(['id'=>$mid])->value('top_mid');
        return $top_mid;
    }

    //获取门店所属商户
    public function get_cardid_mid($mid){
        $Merchant = new Merchant();
        $top_mid = $Merchant->where(['id'=>$mid])->value('top_mid');
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $card_id = $CardMember->where(['top_mid'=>$top_mid])->value('card_id');
        if (!$card_id){
            $card_id = $CardGeneral->where(['top_mid'=>$top_mid])->value('card_id');
        }
        return $card_id;
    }
    //获取公众号二维码
    public function getwxqrcode()
    {

        $arr = request()->param();
        $Cardmember = new CardMember();
        $Momerchant = new Momerchant();
        $WxOpen = new WxOpen();
        $map['top_mid'] = $Cardmember->where(['card_id' => $arr['card_id']])->value('top_mid');
        $wx_open_id = $Momerchant->where($map)->value('wx_open_id');
        $qrcode = $WxOpen->where(['id' => $wx_open_id])->value('qrcode');
        if ($qrcode) {
            $data['code'] = 0;
            $data['message'] = 0;
            $data['date'] = $qrcode;
        } else {
            $data['code'] = 9001;
            $data['message'] = 0;
            $data['date'] = '';
        }
        return json($data);
    }

    //获取用户信息
//    public function getcarduser($arr){
//        $map['card_id'] = $arr['card_id'];
//        $map['openid'] = Session::get('card_openid');
//        $CardUserGet = new CardUserGet();
//        $user = $CardUserGet->where($map)->field('openid,card_id,code,qrcode,nickname,name,phone,bonus,balance,have,fire')->find();
//        if ()
//    }

    //微信API参数  根据card_id获取
    /*
     * $card_id
     */
    public function options($card_id)
    {
        //  Session::set('openid', null);
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $Merchant = new Merchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent=new Agent();
        $mid = $CardMember->where('card_id', $card_id)->value('mid');
        if ($mid) {
            $map['id'] = $mid;
        } else {
            $map['id'] = $CardGeneral->where('card_id', $card_id)->value('mid');
        }
        $merchantinfo=$Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->field('component_token,component_encodingaeskey,component_appid,component_appsecret,open_ticket')->find();
       $config=$Agent->where(array('id'=>$merchantinfo['agent']))->find();
        $users = $WxOpen->where($mab)->field('authorizer_appid,authorizer_refresh_token')->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    public function option($mid)
    {
        //  Session::set('openid', null);
        $Merchant = new Merchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent=new Agent();
        $map['id'] = $mid;
        $merchantinfo=$Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
//        $config = $System->where(array('id' => 1))->field('component_token,component_encodingaeskey,component_appid,component_appsecret,open_ticket')->find();
        $config=$Agent->where(array('id'=>$merchantinfo['agent']))->find();

        $users = $WxOpen->where($mab)->field('authorizer_appid,authorizer_refresh_token')->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    //生成二维码
    public function qrcode($arr)
    {
        $Qrcodes = new Qrcodes();
        $res = $Qrcodes->cardqrcode($arr);
        if ($res) {
            return $res;
        } else {
            $res = '0';
            return $res;
        }
    }

    //空操作
    /*
     * 跳转404
     */
    public function _empty()
    {
        return $this->fetch('public/404');
    }

    //检查异常
    public function chack_abn($param){
        if ($param['status'] == "2"){
            $this->redirect('mobilebase/abnormal');
        }
    }

    //异常页面
    public function abnormal(){
        return $this->fetch('public/abnormal');
    }
}
